package com.forrest.party;

import com.forrest.common.model.Party;
import com.forrest.common.model.Ptp;
import com.jfinal.aop.Duang;
import com.jfinal.kit.Ret;

import java.util.Date;
import java.util.List;

public class PartyService {

    public static final PartyService me = Duang.duang(PartyService.class);
    private static final Party partyDao = new Party().dao();
    private static final Ptp ptpDao = new Ptp().dao();

    public Ret newParty(String partyname, String partyowner, Date partytime, String partyplace, String avator, int status) {
        Party party = new Party();
        if (!party.setPartyname(partyname).setPartyowner(partyowner).setPartytime(partytime).setPartyplace(partyplace).setAvator(avator).setStatus(status).save()) {
            return Ret.by("status", false).set("msg", "未知错误");
        } else {
            return Ret.by("status", true);
        }
    }

    public List<Party> myOwn(String partyowner) {
        return partyDao.find(partyDao.getSqlPara("party.findByPartyOwnerAndStatus", partyowner, 1));
    }

    public List<Party> waiting(String partyowner) {
        return partyDao.find(partyDao.getSqlPara("party.findByPartyOwnerAndStatus", partyowner, 0));
    }

    public List<Party> myJoin(String participant) {
        List<Party> partyList = partyDao.find(partyDao.getSqlPara("party.findByStatus", 2));
        List<Ptp> ptpList = ptpDao.find(ptpDao.getSqlPara("ptp.findByParticipant", participant));
        if (!ptpList.isEmpty()) {
            for (Ptp aPtpList : ptpList) {
                partyList.add(partyDao.findById(aPtpList.getParty()));
            }
        }
        return partyList;
    }

    public List<Party> display() {
        return partyDao.find(partyDao.getSqlPara("party.findByStatus", 1));
    }

    public List<Party> manage() {
        return partyDao.find(partyDao.getSqlPara("party.findByStatus", 0));
    }

    public Ret joinParty(int partyid, String participant, int status) {
        Ptp ptp = new Ptp();
        if (ptp.setParty(partyid).setParticipant(participant).setStatus(status).save()) {
            return Ret.by("status", true);
        } else {
            return Ret.by("status", false).set("msg", "未知错误");
        }
    }

    public String participant(int partyId) {
        List<Ptp> ptpList = getParticipant(partyId);
        StringBuilder participant = new StringBuilder();
        for (Ptp aPtpList : ptpList) {
            participant.append(aPtpList.getParticipant()).append(" ");
        }
        return participant.toString();
    }

    public List<Ptp> getParticipant(int partyId) {
        return ptpDao.find(ptpDao.getSqlPara("ptp.findByPartyId", partyId));
    }

    public Ret allow(int id) {
        Party party = partyDao.findById(id);
        if (party.setStatus(1).update()) {
            return Ret.by("status", true);
        } else {
            return Ret.by("status", false).set("msg", "未知错误");
        }
    }

}
